package com.yishusmt.wechatapi.wechatdev.utils;

import com.yishusmt.wechatapi.wechatdev.constant.WeChatConstant;
import com.yishusmt.wechatapi.wechatdev.constant.MenuConstant;
import com.yishusmt.wechatapi.wechatdev.entity.AccessToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.net.URISyntaxException;

/**
 * 创建菜单
 *
 * @author zhangyi
 * @date 2018/8/28 10:29
 */
@Slf4j
@Component
public class MenuUtil {

    @Autowired
    private AccessTokenUtil accessTokenUtil;

    @Autowired
    private HttpClientUtil httpClientUtil;

    /**
     * 创建微信菜单
     *
     * @return
     */
    public String createMenu() throws IOException, URISyntaxException {
        AccessToken accessToken = accessTokenUtil.getAccessToken();
        String url = MenuConstant.menuUrl.replace(WeChatConstant.ACCESS_TOKEN,
                accessToken.getAccess_token());
        File file = ResourceUtils.getFile("classpath:wechatResource/menu.json");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        String str = "";
        StringBuffer menu = new StringBuffer(str);
        while((str = bufferedReader.readLine()) != null){
            menu.append(str);
        }

        System.out.println(menu.toString());

        String s = httpClientUtil.postConnect(url, menu.toString());
        if(StringUtils.contains(s,"0") || StringUtils.contains(s,"ok")){
            log.info("菜单创建成功！");
            return "ok -> 菜单创建成功！";
        }else{
            log.error("菜单创建失败："+s);
            return "fail"+"菜单创建失败";
        }
    }

    /**
     *  获取菜单文件
     *
     * @return
     * @throws IOException
     * @throws URISyntaxException
     */
    public String getMenuFile() throws IOException {
        File file = ResourceUtils.getFile("classpath:wechatResource/menu.json");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        String s;
        StringBuffer str = new StringBuffer();
        while((s = bufferedReader.readLine()) != null){
            str.append(s);
        }
        return str.toString();
    }

    /**
     * 修改菜单文件
     *
     * @return
     * @throws IOException
     * @throws URISyntaxException
     */
    public void editMenuFile(String menuResource) throws IOException {
        File file = ResourceUtils.getFile("classpath:wechatResource/menu.json");
        System.out.println(file.getAbsolutePath());
        BufferedWriter bufferedWriter =
                new BufferedWriter(new FileWriter(file,false));
        bufferedWriter.write(menuResource);
        bufferedWriter.flush();
    }
}
